package com.hanson.filter;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.hanson.common.api.CommonResult;
import com.hanson.common.api.ResultCode;
import com.hanson.common.constant.Constant;
import com.hanson.pojo.vo.TbIpList;
import com.hanson.pojo.vo.TbIpVisitLog;
import com.hanson.service.ITbIpListLogService;
import com.hanson.service.ITbIpListService;
import com.hanson.service.ITbIpVisitLogService;
import com.hanson.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Deprecated
public class IpFilter implements Filter {

    @Autowired
    ITbIpListService ipListService;
    @Autowired
    ITbIpListLogService ipListLogService;
    @Autowired
    ITbIpVisitLogService visitLogService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ip = IpUtils.getEffectiveIp(IpUtils.getIpAddr(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()));
        TbIpList ipList = new TbIpList();
        ipList.setIp(ip).setStatus(Constant.DELETE_FLAG_CLOSE).setType(Constant.BLACK_LIST_IP);
        Integer exist = ipListService.selectCount(ipList);
        if (exist > 0){
            //拦截黑名单
            CommonResult<Object> result = new CommonResult<>(ResultCode.BLACK_LIST,null);
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.getWriter().write(JSONObject.toJSONString(result));
            return;
        }
        //记录ip浏览记录
        String ipOffLine = IpUtils.getIpOffLine(ip);
        Integer visitDate = Integer.valueOf(DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN));
        TbIpVisitLog visitLog = new TbIpVisitLog();
        visitLog.setIp(ip).setVisitDate(visitDate).setStatus(Constant.DELETE_FLAG_CLOSE);
        Integer existLog = visitLogService.selectCount(visitLog);
        if (existLog <= 0){
            visitLog.setIpAddress(ipOffLine)
                    .setCreateBy(Constant.ADMIN_USER);
            visitLogService.add(visitLog);
        }else {
            visitLogService.update(visitLog);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}